package current;

import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLock拥有比Synchronized更好的中断能力
 */
public class ReentrantLockInterruptDemo {

    private final Object lock = new Object();

    private final ReentrantLock reentrantLock = new ReentrantLock();

    /**
     * 不能中断
     */
    private Thread synchronizedInterrupt() {
        Thread t = new Thread(() -> {
            synchronized (lock) {
                for (int i = 0; i < 1000000000; i++);
                System.out.println("finished.");
            }
        });
        return t;
    }

    /**
     * 可以中断
     */
    private Thread reentrantLockInterrupt() {
        Thread t = new Thread(() -> {
            int k = 0;
            try {
                reentrantLock.lockInterruptibly();
                for (int i = 0; i < 1000000000; i++) {
                    k+=1;
                }
                System.out.println("finished." + k);
            } catch (InterruptedException e) {
                System.out.println("Interrupted." + k);
                e.printStackTrace();
            } finally {
                reentrantLock.unlock();
            }
        });
        return t;
    }

    public static void main(String[] args) {
        ReentrantLockInterruptDemo demo = new ReentrantLockInterruptDemo();
//        Thread t = demo.synchronizedInterrupt();
        Thread t = demo.reentrantLockInterrupt();
        t.start();
        t.interrupt();
    }
}
